//
//  MainViewController.m
//  Flashlight
//
//  Created by Eric on 11/25/12.
//  Copyright (c) 2012 Saick. All rights reserved.
//

#import "TorchManage.h"
#import "MainViewController.h"
#import "SQLibs.h"
#import "TorchConfig.h"
#import "global_Header.h"
#import "MoreDetailViewController.h"
#import "WhiteTorchViewController.h"

#define kTorchButtonHeight  40.0f

@interface MainViewController ()

@end

@implementation MainViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [_scroll release];
    [_background release];
    [_lbLCD release];
    
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
	// Do any additional setup after loading the view, typically from a nib.
    /*    if (_vcSetting == nil)
     _vcSetting = [[SettingViewController alloc] init];
     
     _vcSetting.view.frame = CGRectMake(320.0f-45.0f, 150.0f, 228.0f, 200.0f);
     
     if (_vcSetting.view.superview == nil)
     [self.view addSubview:_vcSetting.view];
     */
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(restoreScrollViewPosition)
                                                 name:kNotifRestoreMainScrollPosition
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moveonScrollViewPosition)
                                                 name:kNotifMoveOnMainScrollPosition
                                               object:nil];
    
    [_scroll setContentSize:CGSizeMake(_scroll.frame.size.width, kTorchButtonHeight * 5 + 30.0f)];
    
    [self torchMonitor];
    [self initLCDShow];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [MobClick beginLogPageView:@"MainViewController"];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [MobClick endLogPageView:@"MainViewController"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotate
{
    return NO;
}

#pragma mark - Flipside View

- (void)moreViewControllerDidFinish:(MoreViewController *)controller
{
    if (kOSVersion >= 5.0f)
        [self dismissViewControllerAnimated:YES completion:nil];
    else
        [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - actions

- (IBAction)showInfo:(id)sender
{
    MoreViewController *controller = [[[MoreViewController alloc] initWithNibName:@"MoreViewController" bundle:nil] autorelease];
    controller.delegate = self;
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
    nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    if (kOSVersion >= 5.0)
        [self presentViewController:nav animated:YES completion:nil];
    else
        [self presentModalViewController:nav animated:YES];
    [nav release];
}

- (IBAction)torchBtnPressed:(id)sender
{
    [UIView animateWithDuration:0.2f animations:^{
        if ([TorchManage defaultManager].fTorchLevel == 0.0f) {
            [_scroll setContentOffset:CGPointMake(0.0f, kTorchButtonHeight * 2)];
            [[TorchManage defaultManager] showTorch:1.0f];
        } else {
            [_scroll setContentOffset:CGPointMake(0.0f, 0.0f)];
            [[TorchManage defaultManager] showTorch:0.0f];
        }
    }];
}

#pragma mark - scroll view delegate

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
        [self controlTorch:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self controlTorch:scrollView];
}

#pragma mark - private

- (void)controlTorch:(UIScrollView *)scrollView
{
    // from 0 - 80
    if (scrollView.contentOffset.y >= 0) {
        if (scrollView.contentOffset.y < kTorchButtonHeight * 3/2 &&
            scrollView.contentOffset.y > kTorchButtonHeight / 2 && kOSVersion >= 6.0f) {
            [UIView animateWithDuration:0.2f animations:^{
                [scrollView setContentOffset:CGPointMake(0.0f, kTorchButtonHeight)];
            } completion:^(BOOL bFinish) {
                if (bFinish)
                    [self showTorch:0.5f];
            }];
        } else if ((scrollView.contentOffset.y >= kTorchButtonHeight * 3/2 &&
                    scrollView.contentOffset.y <= kTorchButtonHeight * 2) ||
                   (kOSVersion < 6.0f && scrollView.contentOffset.y >= kTorchButtonHeight)) {
            [UIView animateWithDuration:0.2f animations:^{
                [scrollView setContentOffset:CGPointMake(0.0f, kTorchButtonHeight * 2)];
            } completion:^(BOOL bFinish) {
                if (bFinish)
                    [self showTorch:1.0f];
            }];
        } else {
            [UIView animateWithDuration:0.2f animations:^{
                [scrollView setContentOffset:CGPointMake(0.0f, 0.0f)];
            } completion:^(BOOL bFinish) {
                if (bFinish)
                    [self showTorch:0.0f];
            }];
        }
    } // end of if (scrollView.contentOffset.y >= 0) {
}

- (void)showTorch:(float)fLevel
{
    [[TorchManage defaultManager] showTorch:fLevel];
}

- (void)torchMonitor
{
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [captureDevice addObserver:self
                    forKeyPath:@"torchMode"
                       options:NSKeyValueObservingOptionPrior
                       context:nil];
}

#pragma mark - kvo

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"torchMode"]) {
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if (captureDevice.torchMode == AVCaptureTorchModeOn) {
            [_background setHighlighted:YES];
        } else {
            [_background setHighlighted:NO];
        }
    }
}

#pragma mark - touch

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    if ([TorchConfig sharedConfig].isEnableFullScreenControl) {
        if ([AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo].torchMode == AVCaptureTorchModeOn)
        {
            // 已经打开的话，就不再处理，只能按常规方法关闭
            return;
        }
        [self torchBtnPressed:nil];
    }
}

#pragma mark - custom notif

- (void)restoreScrollViewPosition
{
    [_scroll setContentOffset:CGPointMake(0.0f, 0.0f)];
}

- (void)moveonScrollViewPosition
{
    if (_scroll.contentOffset.y == 0)
        [_scroll setContentOffset:CGPointMake(0.0f, kTorchButtonHeight * 2)];
}

#pragma mark - LCD

- (void)initLCDShow
{
    if (_lbLCD == nil)
        _lbLCD = [[UILabel alloc] initWithFrame:CGRectMake(54.0f, 160.0f, 220.0f, 25.0f)];
    
    //    _lbLCD.text = @"---------------";   // 共15个
    _lbLCD.text = @"";
    _lbLCD.font = [UIFont fontWithName:@"DBLCDTempBlack" size:22];
    _lbLCD.textColor = [UIColor greenColor];
    _lbLCD.textAlignment = UITextAlignmentLeft;
    _lbLCD.backgroundColor = [UIColor clearColor];
    
    if (_lbLCD.superview == nil)
        [self.view addSubview:_lbLCD];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLCD:) name:kNotifUpdateLCD object:nil];
}

static int nTotal = 0;

- (void)animateLCD:(NSNumber *)nnTotal
{
//    int nTotal = [nnTotal intValue];
    NSString *strText = [_lbLCD.text copy];
    if (nTotal < 0) {
        _lbLCD.text = [strText stringByAppendingString:@"-"];
        nTotal ++;
    } else if (nTotal > 0) {
        int nLength = strText.length;
        if (strText.length > nLength - 1)
            _lbLCD.text = [strText substringToIndex:nLength - 1];
        else
            _lbLCD.text = @"";
        nTotal --;
    }
    [strText release];
    
    SQLOG(@"%@, %d", _lbLCD.text, nTotal);
    
    if (nTotal != 0)
        [self performSelector:@selector(animateLCD:) withObject:[NSNumber numberWithInt:nTotal] afterDelay:0.01f];
}

- (void)updateLCD:(NSNotification *)notif
{
    CGFloat fLevel = fabs([[notif.userInfo objectForKey:@"level"] floatValue]);
    
    NSString *strTotal = @"---------------";
    NSInteger nLength = fLevel * 15;
    NSString *strOld = _lbLCD.text;
    NSString *strLCD = [strTotal substringToIndex:nLength];
    
//    NSInteger nTotal = strOld.length - strLCD.length;
//    
//    static NSNumber* nnTotal = nil;
//    nnTotal = [NSNumber numberWithInt:nTotal];
    nTotal = strOld.length - strLCD.length;
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(animateLCD:) object:nil];
    [self performSelector:@selector(animateLCD:) withObject:nil afterDelay:.2f];
}

@end
